<template>
  <div>
    <el-card class="table-card">
      <div slot="header">
        <h4>{{isEdit ? '编辑采购类型配置' : '新增采购类型配置'}}</h4>
      </div>
      <BtnRender :render="renderBtnsBar" />
      <el-form class="purchase-form" size="mini" ref="purchaseForm" :model="purchaseForm" label-width="100px">
        <el-form-item  label="发起原因：" :rules= "[{ required: true }]">
          <el-input maxlength="2000" :rows="1" type="textarea" v-model.trim="purchaseForm.reason" />
        </el-form-item>
      </el-form>
      <el-row>
        <skus-table
          showActionCol
          :actionColWidth="80"
          :columns="tableInfo.columns"
          :loading="tableInfo.loading"
          :dataSource="tableInfo.list"
          :actionRender="tableBtnAction"
        />
      </el-row>
    </el-card>
    <!-- 品牌选择 -->
    <SelectBrandDialog
      :visible.sync="brandVisible"
      :categoryNo="currentRow.categoryCode"
      @getBrandInfo="handleBrandSelect"
    />
    <!-- 部门选择 -->
    <SelectDeptDialog
      :visible.sync="deptVisible"
      :hrAreaId="currentRow.areaId"
      @deptSelected="handleDeptSelect"
    />
  </div>
</template>
<script>
import SkusTable from '@/components/skusTable';
import { createExcelByExport } from '@/utils/bizUtils';
import {
  queryConfigDetailByIdsService,
  queryConfigDetailByRecordService,
  exportPurchaseTypeTemplateService,
  savePurchaseTypeConfigService,
  submitPurchaseTypeConfigService,
} from '@/api/sourcing/purchaseType';
import { queryAreasService } from '@/api/sourcing/public'
import SelectBrandDialog from '@/pages/sourcing/components/SelectBrandDialog';
import SelectDeptDialog from '@/pages/sourcing/components/SelectDeptDialog';
import BtnRender from '@/components/JSXRender/BtnRender';
import { getBtnsBar } from '@/utils/getBtnsRender';
import { ERRORS_COLUMN, TYPE_OPTIONS } from './constants'

export default {
  components: {
    SkusTable,
    SelectBrandDialog,
    BtnRender,
    SelectDeptDialog
  },
  data () {
    return {
      SelectCategory: () => import('@/pages/sourcing/components/CategorySearch'),
      key: 1,
      brandVisible: false,
      deptVisible: false,
      submitLoading: false,
      importLoading: false,
      exportLoading: false,
      currentRow: {},
      purchaseForm: {
        reason: ''
      },
      idList: [],
      recordId: '',
      tableInfo: {
        loading: false,
        list: [],
        columns: []
      },
      areaList: []
    };
  },
  computed: {
    // 编辑来源 0 审批完成 1 待审批
    sourceType () {
      if (this.idList.length !== 0) {
        return 0
      }
      if (this.recordId) {
        return 1
      }
      return 0
    },
    isEmpty () {
      return this.tableInfo.list.length === 0
    },
    isEdit () {
      return this.idList.length !== 0 || this.recordId;
    },
    ids () {
      if (this.isEdit && this.idList.length !== 0) {
        return this.tableInfo.list.map(item => item.purchaseTypeConfigId)
      }
      if (this.isEdit && this.recordId) {
        return this.tableInfo.list.map(item => item.purchaseTypeConfigAuditId)
      }
      return []
    }
  },
  mounted () {
    this.queryAreaList();
    this.initTableData();
    // this.initTableColumns();
  },
  methods: {
    // 获取区域数据
    async queryAreaList () {
      const res = await queryAreasService()
      if (res) {
        this.areaList = res.data.map(item => ({
          label: item.areaName,
          value: item.areaId
        }))
        this.initTableColumns();
      }
    },
    // 初始化表格数据
    initTableData () {
      const { idList } = this.$route.params;
      const { auditRecordId } = this.$route.query;
      if (idList) {
        this.idList = idList;
        this.getTableDataByIds();
      }
      if (auditRecordId) {
        this.recordId = auditRecordId;
        this.getTableDataByRecordId();
      }
      if (!this.isEdit) {
        this.handleAdd(1)
      }
    },
    // 初始化表头
    initTableColumns () {
      // this.tableInfo.columns = _.cloneDeep(initConfigTableColumns(this))
      this.tableInfo.columns = [
        {
          title: '品类树',
          key: 'fullPath',
          width: 120
        },
        {
          title: '分类名称',
          key: 'categoryName',
          required: true,
          width: 100,
          render: (h, { row, index }) => {
            if (!this.recordId && this.isEdit) {
              return <span>{row.categoryName}</span>
            }
            const SelectCategory = this.SelectCategory
            return <SelectCategory
              setName={true}
              value={row.categoryName}
              brandId={row.brandId}
              onOnSelected={ (data) => { this.handleCategorySelected(data, row, index) }}
            />
          }
        },
        {
          title: '分类代码',
          key: 'categoryCode',
          required: true,
        },
        {
          title: '品牌ID',
          key: 'brandId',
          required: true,
        },
        {
          title: '品牌名称',
          key: 'brandName',
          required: true,
          width: 100,
          render: (h, { row, index }) => {
            if (!this.recordId && this.isEdit) {
              return <span>{row.brandName}</span>
            }
            return <el-input
              clearable
              value={row.brandName}
              prefix-icon="el-icon-search"
              onFocus={() => { this.showDialog(row, 'brand') }}
              placeholder="请选择品牌"
              onClear={() => { row.brandId = ''; row.brandName = '' }}
            />
          }
        },
        {
          title: '区域名称',
          key: 'areaId',
          required: true,
          width: 100,
          render: (h, { row }) => {
            return <el-select
              v-model={row.areaName}
              onChange={val => { this.handleSelectChange({ val, row, columnName: 'areaId' }) }}
            >
              { this.areaList.map(item => <el-option key={item.value} value={item.value} label={item.label} />) }
            </el-select>
          }
        },
        {
          title: '部门名称',
          key: 'hrDeptId',
          required: false,
          width: 100,
          render: (h, { row, index }) => {
            return <el-input
              disabled={!row.areaName || row.purchaseType == 3}
              clearable
              value={row.hrDeptName}
              prefix-icon="el-icon-search"
              onFocus={() => { this.showDialog(row, 'dept') }}
              placeholder="请选择部门"
              onClear={() => { row.hrDeptId = ''; row.hrDeptName = '' }}
            />
          }
        },
        {
          title: '采购类型',
          key: 'purchaseType',
          required: true,
          render: (h, { row }) => {
            return <el-select
              v-model={row.purchaseType}
              onChange={val => { this.handleSelectChange({ val, row, columnName: 'purchaseType' }) }}
            >
              { TYPE_OPTIONS.map(item => <el-option key={item.value} value={item.value} label={item.label} />) }
            </el-select>
          }
        },
      ]
    },
    // 初始化操作按钮
    renderBtnsBar (h) {
      const btns = [
        {
          label: '增加行',
          method: () => { this.handleAdd(1) },
        },
        {
          label: '增加10行',
          method: () => { this.handleAdd(10) },
        },
        {
          label: '增加50行',
          method: () => { this.handleAdd(50) },
        },
        {
          label: '模板导入',
          action: 'srm-api/purchaseTypeConfig/importTemplate',
          methods: { handleUploadSuccess: this.handleUploadSuccess },
          isImport: true,
          data: { idList: this.ids, type: this.sourceType },
          loadingFn: state => { this.importLoading = state },
        },
        {
          label: '模板导出',
          method: this.handleExportTemplate,
          loading: this.exportLoading,
        },
        {
          label: '暂存',
          method: this.saveAction,
          loading: this.submitLoading,
          disabled: this.isEmpty
        },
        {
          label: '提交',
          method: this.handleSubmit,
          loading: this.submitLoading,
          disabled: this.isEmpty
        },
        {
          label: '取消',
          method: this.handleBack,
        },
      ];
      if (this.isEdit) {
        btns.splice(0, 3)
      }
      btns.forEach(item => {
        item.size = 'medium'
      })
      return getBtnsBar(h, btns);
    },
    // 渲染表格操作栏按钮
    tableBtnAction (h, { index, row }) {
      return (
        <div class="table-action">
          <el-button type="text" onClick={() => this.handleDelete(index)}>
            删除
          </el-button>
        </div>
      );
    },
    // 获取表格数据通过idList
    async getTableDataByIds () {
      const res = await queryConfigDetailByIdsService(
        this.idList,
        state => { this.tableInfo.loading = state }
      );
      if (res?.data) {
        this.tableInfo.list = res.data
      }
    },
    // 获取表格数据通过单据号
    async getTableDataByRecordId () {
      const res = await queryConfigDetailByRecordService(
        { auditRecordId: this.recordId },
        state => { this.tableInfo.loading = state }
      );
      if (res?.data) {
        const { remark, dataList } = res.data
        this.tableInfo.list = dataList
        this.purchaseForm.reason = remark
      }
    },
    // 导入成功
    handleUploadSuccess (res) {
      this.importLoading = false;
      const { code, data, msg } = res;
      if (code == 200) {
        this.tableInfo.list = data;
      } else {
        this.$message.error(msg);
      }
    },
    // 导出信息数据
    async handleExportTemplate () {
      const res = await exportPurchaseTypeTemplateService(
        { idList: this.ids, type: this.sourceType },
        state => { this.exportLoading = state; }
      );
      createExcelByExport({ res, excelTitle: '采购类型模板' });
    },
    // 选择品类
    handleCategorySelected (data = {}, row) {
      const { categoryNo = '', fullpath = '', categoryName = '' } = data || {}
      row.categoryName = categoryName
      row.categoryCode = categoryNo
      row.fullPath = fullpath
    },
    showDialog (row, type) {
      this[`${type}Visible`] = true;
      this.currentRow = row;
    },
    // 品牌选择
    handleBrandSelect (data) {
      const { brandName, uuid } = data;
      this.currentRow.brandId = uuid
      this.currentRow.brandName = brandName
    },
    // 部门选择
    handleDeptSelect (data) {
      const { hrDepartmentName, hrDepartmentId } = data;
      this.currentRow.hrDeptId = hrDepartmentId
      this.currentRow.hrDeptName = hrDepartmentName
    },
    // 新增行
    handleAdd (length) {
      for (let i = 0; i < length; i++) {
        this.tableInfo.list.push(
          {
            key: this.key++,
            fullPath: '',
            categoryName: '',
            categoryCode: '',
            brandId: '',
            brandName: '',
            areaId: '',
            areaName: '',
            purchaseType: null,
            hrDeptId: '',
            hrDeptName: '',
          }
        )
      }
    },
    // 删除行
    handleDelete (index) {
      this.tableInfo.list.splice(index, 1);
    },
    // 组合提交暂存参数
    generateParams () {
      return {
        auditRecordId: this.recordId,
        remark: this.purchaseForm.reason,
        dataList: this.tableInfo.list
      }
    },
    // 暂存
    async saveAction () {
      const res = await savePurchaseTypeConfigService(
        { ...this.generateParams() },
        state => { this.submitLoading = state }
      );
      if (res) {
        this.submitSuccessCallback()
      }
    },
    // 提交接口请求
    async submitAction () {
      const res = await submitPurchaseTypeConfigService(
        { ...this.generateParams() },
        state => { this.submitLoading = state }
      );
      if (res?.data) {
        const { hasErrorMsg, data } = res.data
        if (hasErrorMsg) {
          this.$message.error('存在异常数据，请编辑后重新提交')
          this.initTableColumns()
          this.tableInfo.columns.unshift(ERRORS_COLUMN)
          this.tableInfo.list = data
        } else {
          this.submitSuccessCallback()
        }
      }
    },
    // 提交校验
    handleSubmit () {
      if (!this.purchaseForm.reason) {
        return this.$message.warning('发起原因不能为空')
      }
      // 校验固定必填字段
      const requiredFields = this.tableInfo.columns.filter(item => item.required).map(item => item.key)
      let hasEmptyVal = false
      this.tableInfo.list.map((item) => {
        Object.keys(item).forEach(ele => {
          if (requiredFields.includes(ele) && item[ele] !== 0 && !item[ele]) {
            hasEmptyVal = true;
          }
        })
      })
      if (hasEmptyVal) {
        return this.$message.warning('请完善必填字段')
      }
      this.submitAction()
    },
    submitSuccessCallback () {
      this.$message.success('操作成功')
      this.$router.push({ name: 'configAuditList' })
    },
    // 取消
    handleBack () {
      this.$router.go(-1)
    },
    handleSelectChange (data) {
      const { row, columnName, val } = data
      // 区域选择
      if (columnName == 'areaId') {
        row.areaId = val
        row.hrDeptId = ''
        row.hrDeptName = ''
        // 区域为集团时采购类型为集采
        if (row.areaId == '1001') {
          row.purchaseType = 1
        } else {
          if (row.purchaseType == 1) {
            row.purchaseType = null
          }
        }
      }
      // 采购类型
      if (columnName == 'purchaseType') {
        // 采购类型为集采时且区域不为集团时，将区域设置为集团
        if (val == 1 && row.areaId !== '1001') {
          row.areaId = '1001'
          row.areaName = '集团总部'
          row.hrDeptId = ''
          row.hrDeptName = ''
        }
        // 采购类型为区采或分采时，且区域为集团时清空区域与部门 分采，部门名称需清空，并且非必填
        if (val != 1 && row.areaId == '1001') {
          row.areaId = ''
          row.areaName = ''
          row.hrDeptId = ''
          row.hrDeptName = ''
        }
        if (val == 3) {
          row.hrDeptId = ''
          row.hrDeptName = ''
        }
      }
    }
  }
};
</script>
<style scoped>
.upload-wrap {
  margin-right: 10px;
}
.tooltip li {
  margin-bottom: 5px;
}
.purchase-form .el-form-item {
  margin-bottom: 0px;
}
</style>
